<script setup name="ofcode">
// import SelectForm from '@/components/p-components/XiaoheSelect'
import { ElButton, ElDialog } from 'element-plus'
import { Top, Bottom } from '@element-plus/icons-vue'
import {
  GetCodeSelAPI,
  GetListAPI,
  AddDataAPI,
  DelDataAPI,
  EditDataAPI,
  GetDelDataAPI,
} from '@/api/system/ofcode'
const { proxy } = getCurrentInstance()

const router = useRouter()
// 封装 方法 字典查询
const {
  sys_ofcode_type, // 编码类型
  sys_ofcode_segment, // 码段
  sys_ofcode_variable, //变量
  sys_ofcode_fill, // 填充方式
} = proxy.useDict(
  'sys_ofcode_type',
  'sys_ofcode_segment',
  'sys_ofcode_variable',
  'sys_ofcode_fill'
)

console.log(sys_ofcode_fill, 'sys_ofcode_fill')
const SelectList = ref([
  { label: '', type: '日期范围' },
  {
    label: '配置类型',
    model: 'ofCodeType',
    type: '下拉单选',
    opt: sys_ofcode_type,
  },
  {
    label: '配置编码',
    model: 'ofCodeStr',
    type: '输入框',
    placeholder: '请输入字段编码',
  },
  {
    label: '配置名称',
    model: 'ofCodeName',
    type: '输入框',
    placeholder: '请输入字段名称',
  },
])

const ruleFormRef = ref(null)

// 列表数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 列表加载
const loading = ref(false)

// 保存按钮加载
const BtnLoading = ref(false)

// 信息展示状态
const Drawer = ref(false)

// 变量下拉
const bianliang = ref([])

const bianliang1 = ref([])
// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  ofCodeType: '',
  ofCodeStr: '',
  ofCodeName: '',
  selectTime: '',
})

// 选中ID
const Ids = ref([])

// 是否禁用修改按钮
const Single = ref(false)

// 是否禁用删除按钮
const Multiple = ref(false)

// 按钮枚举数据
const ButtonList = ref([
  { type: 'add', hasPermi: 'system:codeRule:add', Multiple },
  { type: 'remove', hasPermi: 'system:codeRule:remove', Multiple },
  { type: 'edit', hasPermi: 'system:codeRule:edit', Single },
  { label: '配置变量', type: 'zdy', hasPermi: 'system:codeRule:config' },
])

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = (selection) => {
  Ids.value = selection.map((item) => item.ofCodeId)
  Single.value = selection.length != 1
  Multiple.value = !selection.length
}
handleSelectionChange([])
// 新增
const add = () => {
  Form.value = { ofCodeType: '', ofCodeStr: '', ofCodeName: '', remark: '' }
  TableForm.value = []
  title.value = '新增'
  dialogVisible.value = true
}

// 修改
const edit = async (val) => {
  let ofCodeId = ''
  val ? (ofCodeId = val) : (ofCodeId = Ids.value.join(','))
  title.value = '修改'
  const res = await GetDelDataAPI(ofCodeId)
  Form.value = res
  Form.value.ofCodeType = String(res.ofCodeType)
  Form.value.ofCodeStr = String(res.ofCodeStr)

  TableForm.value = res.inList
  dialogVisible.value = true
}

// 删除
const remove = async (val) => {
  const MesBox = await proxy.DelMessageBox()
  // val.ofCodeId
  if (!MesBox) return
  // console.log(Ids.value.length)
  const res = await DelDataAPI(
    Ids.value.length <= 0 ? val.ofCodeId : Ids.value.join(',')
  )
  if (res.code !== 200) return
  proxy.successMsg('删除成功')

  getList()
}

// 配置变量
const Configuration = () => {}

// 查看
const Look = async (val) => {
  const res = await GetDelDataAPI(val)
  Form.value = res
  title.value = '查看'
  TableForm.value = res.inList
  // console.log(TableForm.value, 'TableForm')
  dialogVisible.value = true
}
// 新增提交
const addSub = async () => {
  try {
    const IsSubmit = await ruleFormRef.value.validate()
    const IsCheck = await Check()
    console.log('-====')

    if (!IsSubmit) return
    if (IsCheck) return
    BtnLoading.value = true
    Form.value.op = JSON.stringify(TableForm.value)
    await AddDataAPI(Form.value)
    dialogVisible.value = false
    proxy.successMsg('添加成功')
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 修改提交
const editSub = async () => {
  try {
    const IsSubmit = await ruleFormRef.value.validate()
    const IsCheck = await Check()
    console.log('-====', IsCheck)

    if (!IsSubmit) return
    if (IsCheck) return
    BtnLoading.value = true
    Form.value.op = JSON.stringify(TableForm.value)
    await EditDataAPI(Form.value)
    dialogVisible.value = false
    BtnLoading.value = false
    proxy.successMsg('修改成功')
    getList()
  } catch (err) {
    // console.log(err)
  } finally {
    BtnLoading.value = false
  }
}

const dialogVisible = ref(false)
const title = ref('新增')

// 弹窗消失时
const close = () => {
  Form.value = { ofCodeType: '', ofCodeStr: '', ofCodeName: '', remark: '' }
  TableForm.value = [
    {
      ind: 0,
      infoSegment: null, // 码段
      infoVariable: '', // 变量
      infoTheLength: 0, // 长度
      infoMethod: 0, // 填充方式
      infoMethodCharacter: 0, // 填充字符
      infoTheNumber: 0, // 起始流水
    },
  ]

  dialogVisible.value = false
  BtnLoading.value = false
}

/**
 *  弹窗新增 表单数据
 */
const Form = ref({
  ofCodeType: '',
  ofCodeStr: '',
  ofCodeName: '',
  remark: '',
})

// 表单枚举数据
const FormList = ref([
  {
    label: '配置类型',
    type: '下拉单选',
    model: 'ofCodeType',
    opt: sys_ofcode_type,
    disabled: title.value == '修改',
  },
  {
    label: '配置编码',
    type: '输入框',
    model: 'ofCodeStr',
    disabled: title.value == '修改',
  },
  { label: '配置名称', type: '输入框', model: 'ofCodeName' },
  { label: '备注', type: '备注框', model: 'remark' },
])

// 校验表单
const Rules = reactive({
  ofCodeType: [
    { required: true, message: '请选择配置类型', trigger: 'change' },
  ],
  ofCodeStr: [
    { required: true, message: '请填写配置编码', trigger: 'blur' },
    { validator: proxy.noChinese, trigger: 'blur' },
  ],
  ofCodeName: [{ required: true, message: '请填写配置名称', trigger: 'blur' }],
})

/**
 *  表格表单
 */

const TableForm = ref([
  {
    infoSegment: null, // 码段
    infoVariable: '', // 变量
    infoTheLength: 0, // 长度
    infoMethod: 0, // 填充方式
    infoMethodCharacter: 0, // 填充字符
    infoTheNumber: 0, // 起始流水
  },
])

// 码段添加
const AddTypeFn = () => {
  // 1 日期变量 2 流水号 3 本文
  TableForm.value.push({
    infoSegment: null, // 码段
    infoVariable: '', // 变量
    infoTheLength: null, // 长度
    infoMethod: null, // 填充方式
    infoMethodCharacter: null, // 填充字符
    infoTheNumber: null, // 起始流水
  })
}
// 删除表格表单
const RemoveTypeFn = (scope) => {
  if (FormTebls.value.length > 0) {
    FormTebls.value.forEach((item) => {
      const Find = TableForm.value.findIndex(
        (itemy) => item.infoId == itemy.infoId
      )
      TableForm.value.splice(Find, 1)
    })
  } else {
    TableForm.value.splice(scope.$index, 1)
  }
}

// 表格表单校验
const Check = async () => {
  console.log('-----------')

  let IsIf = false
  if (TableForm.value.length <= 0) {
    proxy.warningMsg('请填写明细')
    return (IsIf = true)
  }
  console.log('=======')

  await TableForm.value.forEach((item) => {
    if (!item.infoSegment) {
      proxy.warningMsg('请填写码段')
      IsIf = true
      return
    }
    if (item.infoSegment == 1) {
      if (!item.infoVariable) {
        proxy.warningMsg('请填写变量')
        IsIf = true
        return
      }
    } else if (item.infoSegment == 2) {
      if (!item.infoVariable) {
        proxy.warningMsg('请填写变量')
        IsIf = true
        return
      }

      if (!item.infoTheLength) {
        proxy.warningMsg('请填写长度')
        IsIf = true
        return
      }
      if (!item.infoMethod) {
        proxy.warningMsg('请填写填充方式')
        IsIf = true
        return
      }

      if (!item.infoMethodCharacter) {
        proxy.warningMsg('请填充字符')
        IsIf = true
        return
      }
      if (!item.infoTheNumber) {
        proxy.warningMsg('请填写起始流水')
        IsIf = true
        return
      }
    } else {
      if (!item.infoVariable) {
        proxy.warningMsg('请填写变量')
        IsIf = true
        return
      }
    }
  })
  return IsIf
}

// 表格表单排序 向上
const Up = (scope) => {
  window.localStorage.setItem('as', JSON.stringify(scope.row))
  // TableForm.value.unshift([0])
  if (scope.$index >= 1) {
    const Obj = JSON.parse(window.localStorage.getItem('as'))
    TableForm.value.splice(scope.$index - 1, 0, Obj)
    TableForm.value.splice(scope.$index + 1, 1)
  } else {
    // TableForm.value.push(TableForm.value.shift())
  }
}

// 表格表单排序 向下
const Downward = (scope) => {
  // console.log(TableForm.value[scope.$index + 1])
  if (scope.$index != TableForm.value.length - 1) {
    window.localStorage.setItem('as', JSON.stringify(scope.row))
    const Obj = JSON.parse(window.localStorage.getItem('as'))
    TableForm.value.splice(scope.$index + 2, 0, Obj)
    TableForm.value.splice(scope.$index, 1)
  } else {
  }
}

const FormTebls = ref([])

// 表格表单 选中数据
const FormTeblChange = (row) => {
  FormTebls.value = row
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  const res = await GetListAPI(query)
  if (res.code !== 200) return
  total.value = parseInt(res.total)
  TableData.value = res.rows
  loading.value = false
}

// 获取变量下拉
const GetCodeSel = async () => {
  const { data: res } = await GetCodeSelAPI(1)
  bianliang.value = res.theDrop
  const { data: resp } = await GetCodeSelAPI(2)
  bianliang1.value = resp.theDrop
}

// 查询按钮
const selectSubmit = (val) => {
  for (let KEY in val) {
    query[KEY] = val[KEY]
  }
  getList()
}
GetCodeSel()
getList()

const selectChange = (val) => {
  val.infoVariable = ''
  val.infoTheLength = ''
  val.infoMethod = ''
  val.infoMethodCharacter = ''
  val.infoTheNumber = ''
}
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-selectForm :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <!-- 按钮组件 -->
      <el-button
        type="primary"
        @click="add"
        v-hasPermi="['system:codeRule:add']"
        >新增</el-button
      >
      <el-button
        type="danger"
        :disabled="Multiple"
        @click="remove"
        v-hasPermi="['system:codeRule:remove']"
        >删除</el-button
      >
      <el-button
        type="success"
        @click="router.push('/system/business-config/code-rule-data')"
        v-hasPermi="['system:codeRule:config']"
        >配置变量</el-button
      >
      <!-- 表格数据 -->
      <el-table
        style="margin-top: 15px"
        v-loading="loading"
        stripe
        border
        :data="TableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column
          label="配置类型"
          prop="ofCodeType"
          width="auto"
          align="center"
        />
        <el-table-column
          label="配置编码"
          prop="ofCodeStr"
          :show-overflow-tooltip="true"
          width="auto"
          align="center"
        />
        <el-table-column
          label="配置名称"
          prop="ofCodeName"
          :show-overflow-tooltip="true"
          width="auto"
          align="center"
        />
        <el-table-column
          label="备注"
          prop="remark"
          width="180"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="auto"
        />
        <el-table-column
          label="创建人"
          align="center"
          prop="createBy"
          width="auto"
        />
        <el-table-column
          label="操作"
          align="center"
          width="auto"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-link
              type="primary"
              v-hasPermi="['system:codeRule:edit']"
              @click="edit(scope.row.ofCodeId)"
              >修改</el-link
            >
            <el-link
              type="primary"
              v-hasPermi="['system:codeRule:remove']"
              @click="remove(scope.row)"
              >删除</el-link
            >
            <el-link
              type="primary"
              v-hasPermi="['system:codeRule:query']"
              @click="Look(scope.row.ofCodeId)"
              >查看</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="query.pageNum"
          v-model:limit="query.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 弹窗 -->
    <p-dialog
      v-model="dialogVisible"
      width="50%"
      :title="title"
      @close="close"
      @ok="title == '新增' ? addSub() : editSub()"
    >
      <template #body>
        <div>
          <el-form
            ref="ruleFormRef"
            :model="Form"
            :inline="true"
            :rules="Rules"
            label-width="auto"
            label-position="right"
            status-icon
          >
            <el-form-item label="配置类型" prop="ofCodeType">
              <el-select
                :disabled="title == '修改' || title == '查看'"
                clearable
                v-model="Form.ofCodeType"
                placeholder="请输入内容"
              >
                <el-option
                  v-for="(item, index) in sys_ofcode_type"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="配置编码" prop="ofCodeStr">
              <el-input
                :disabled="title == '修改' || title == '查看'"
                clearable
                v-model="Form.ofCodeStr"
                placeholder="请输入内容"
              />
            </el-form-item>
            <el-form-item label="配置名称" prop="ofCodeName">
              <el-input
                :disabled="title == '查看'"
                clearable
                v-model="Form.ofCodeName"
                placeholder="请输入内容"
              />
            </el-form-item>
            <div class="rk">
              <el-form-item label="备注">
                <el-input
                  :disabled="title == '查看'"
                  clearable
                  :rows="2"
                  type="textarea"
                  v-model="Form.remark"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </div>
          </el-form>
          <!-- 表格表单 -->
          <el-card>
            <template #header>
              <div class="card-header" v-if="title != '查看'">
                <div class="card-header-title">明细项</div>
                <div class="caozuo">
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="添加"
                    placement="top-start"
                  >
                    <el-icon @click="AddTypeFn"><Plus /></el-icon>
                  </el-tooltip>
                  <div style="margin: 0 10px"></div>
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="勾选删除"
                    placement="top-start"
                  >
                    <el-icon @click="RemoveTypeFn"><Minus /></el-icon>
                  </el-tooltip>
                </div>
              </div>
            </template>
            <el-table
              class="tableClass"
              v-loading="loading"
              stripe
              border
              :data="TableForm"
              @selection-change="FormTeblChange"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
                fixed="left"
              />
              <el-table-column label="序号" type="index" width="80" />
              <el-table-column label="码段" width="220">
                <template #default="scope">
                  <!-- 下拉 -->
                  <el-select
                    v-model="scope.row.infoSegment"
                    :disabled="title == '查看'"
                    clearable
                    placeholder="请选择"
                    @change="selectChange(scope.row)"
                  >
                    <el-option
                      v-for="(item, index) in sys_ofcode_segment"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="变量" width="220">
                <template #default="scope">
                  <!-- 下拉 -->
                  <el-select
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 1"
                    v-model="scope.row.infoVariable"
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in bianliang"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-select
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 2"
                    v-model="scope.row.infoVariable"
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in bianliang1"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-input
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 3"
                    v-model="scope.row.infoVariable"
                    clearable
                    placeholder="请填写"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="长度" width="220">
                <template #default="scope">
                  <!-- 下拉 -->
                  <el-input
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 2"
                    v-model="scope.row.infoTheLength"
                    clearable
                    type="number"
                    oninput="if(value<=0)value=''"
                    placeholder="请选择"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="填充方式" width="220">
                <template #default="scope">
                  <!-- 下拉 -->
                  <el-select
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 2"
                    v-model="scope.row.infoMethod"
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in sys_ofcode_fill"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="填充字符" width="220">
                <template #default="scope">
                  <el-input
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 2"
                    v-model="scope.row.infoMethodCharacter"
                    clearable
                    placeholder="请填写"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="起始流水号" width="220">
                <template #default="scope">
                  <el-input
                    :disabled="title == '查看'"
                    v-if="scope.row.infoSegment == 2"
                    v-model="scope.row.infoTheNumber"
                    clearable
                    placeholder="请填写"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                v-if="title != '查看'"
                label="操作"
                align="center"
                width="160"
                fixed="right"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <div class="caozuo">
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="向上排序"
                      placement="top-start"
                    >
                      <el-icon
                        size="30"
                        @click="Up(scope)"
                        v-show="scope.$index !== 0"
                        ><Top
                      /></el-icon>
                    </el-tooltip>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="向下排序"
                      placement="top-start"
                    >
                      <el-icon
                        size="30"
                        @click="Downward(scope)"
                        v-show="
                          scope.$index !== TableForm.length - 1 &&
                          scope.$index >= 0
                        "
                        ><Bottom
                      /></el-icon>
                    </el-tooltip>
                    <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="删除"
                      placement="top-start"
                    >
                      <el-icon size="30" @click="RemoveTypeFn(scope)"
                        ><Minus
                      /></el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </template>
    </p-dialog>
    <!-- 信息展示 -->
    <el-drawer size="50%" v-model="Drawer" title="信息展示">
      <el-form :inline="true">
        <el-form-item label="配置类型:">
          <div class="value">{{ Form.codetypeStr }}</div>
        </el-form-item>
        <el-form-item label="配置编码:">
          <div class="value">{{ Form.ofCodeStr }}</div>
        </el-form-item>
        <el-form-item label="配置名称:">
          <div class="value">{{ Form.ofCodeName }}</div>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item label="备注:">
          <div>{{ Form.remark }}</div>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        stripe
        border
        :data="TableForm"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="码段" prop="segS" width="auto" />
        <el-table-column
          label="变量"
          prop="varS"
          :show-overflow-tooltip="true"
          width="auto"
        />
        <el-table-column
          label="长度"
          prop="infoTheLength"
          :show-overflow-tooltip="true"
          width="auto"
        />
        <el-table-column label="填充方式" prop="metS" width="180" />
        <el-table-column
          label="填充字符"
          align="center"
          prop="infoMethodCharacter"
          width="160"
        />
        <el-table-column
          label="起始流水号"
          align="center"
          prop="infoTheNumber"
          width="160"
        />
      </el-table>
    </el-drawer>
  </div>
</template>
<style lang="scss" scoped>
.my-header {
  width: 200px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.card-header-title {
  font-weight: 700;
}
.card-header {
  display: flex;
  justify-content: space-between;
}
.Btn {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  min-width: 160px;
}
.caozuo {
  display: flex;
  justify-content: space-evenly;
}
.value {
  border-bottom: 1px solid #000;
  width: 120px;
}
.rk ::v-deep .el-form-item {
  width: 100% !important;
}
</style>
